package modes

import (
	"fmt"
)

/*
 * 描述: 项目表
 *
 * start 状态  0 启用  1 禁用
 *
 *********************** ******/

type ProjectRe struct {
	Id           int64  `json:"p_id" xorm:"id"`                  //I D
	Name         string `json:"p_name" xorm:"name"`              //项目名称
	Start        int    `json:"p_start" xorm:"start"`            //状态
	ExamAt       int64  `json:"exam_at" xorm:"exam_at"`          //考试时间
	ExamAtState  int    `json:"et_state" xorm:"exam_at_state"`   // 考试时间是否启用 0：启用，1 禁用
	ExamAtUpdate int64  `json:"et_update" xorm:"exam_at_update"` //  考试时间的最后一次更新时间
}

func (this *ProjectRe) TableName() string {
	return "projectre"
}

func (this *ProjectRe) Save() (int64, error) {
	return Db(0).Insert(this)
}

func (this *ProjectRe) Get() (bool, error) {
	return Db(0).Get(this)
}

func (this *ProjectRe) PList(val *Pager) error {

	w := ""
	val.Total, _ = this.Count(w)
	var field string
	//switch ( val.Collatoin ){
	//	case 0: field = "at"        	// 领取时间
	//	case 1: field = "call_at"       // 最近一次的拨打时间
	//	case 2: field = "call_count"	// 拨打次数
	//	case 3: field = "weight"        // 权重
	//}
	list, err := this.where(val.Rules, val.Count, val.Page, w, field)
	if err == nil {
		val.List = list
	}
	return err
}
func (this *ProjectRe) List(id int64) ([]ProjectRe, error) {
	var where string
	if id == 0 {
		where = fmt.Sprintf("id %% 100000 = 0 and start = 0")
	} else if (id % 100000) > 0 {
		where = fmt.Sprintf("id > %d and id < %d and start = 0", id, id+1000)
	} else {
		where = fmt.Sprintf("id > %d and id < %d and start = 0 and id %% 1000 = 0", id, id+100000)
	}
	return this.where(0, 100, 0, where, "")
}

func (this *ProjectRe) Count(where string) (int64, error) {
	var val ProjectRe
	return Db(0).Where(where).Count(&val)
}

func (this *ProjectRe) where(fage, count, page int, where, field string) ([]ProjectRe, error) {
	list := make([]ProjectRe, 0)
	var err error
	if field == "" {
		field = "id"
	}
	page--
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}

func (this *ProjectRe) IdList() ([]ProjectRe, error) {
	//start, end := PIdWhere( 1001000  )
	swhere := fmt.Sprintf("id %% 1000 > 0 and start = 0")
	return this.where(0, 100, 0, swhere, "")
}
